//获取应用实例
const app = getApp()
import FormValidation from '../../../../../utils/formValidation'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //快递列表
    ExpressList: [],
    FrmValidate: null, //验证组件
    OrderPrice: '0', //订单金额
    FeeList: [], //费用列表

    HasDftAddress: false, //是否存在默认地址
    MailUserName: '', //收件名称
    MailUserMobile: '', //收件电话
    MailAreaAddress: '', //收件省市
    MailAddress: '', //收件地址
    MailAddressID: 0, //收件主键

    ExpressCompanyID: 0, //快递公司
    ExpressFee: 0, //快递费用

    BizTypeID: 0, //业务类型

    Compulsory: null, //原机动车号牌图片地址


    provinceShort: '京', //省份简称
    isShowProvinceSelect: false, //是否显示省份选择
    isShowMask: false, //是否显示遮罩
    isShowImgPop: false, //是否显示示例弹窗
    exampleType: 0, //示例类型  0 保单  
    modalHidden: true, //是否隐藏模态框
    modalMsg: '确认删除图片吗？', //模态框信息提示语
    currentDelImgId: null, //当前要删除图片的id   
    isShowBottomPop: false, //是否显示价格明细弹层
    isShowHighZindexMask: false, //是否显示高层级遮罩层
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    this.setData(options);
    //获取订单费用
    this.getOrderPrice();
    //获取邮寄公司
    this.getExpressFee();
    //获取默认收件地址
    this.getDefaultAddress();
    //设置验证
    this.initValidate();
  },
  /**
   *  表单提交
   */
  formSubmit: function (e) {
    let self = this;
    const data = e.detail.value
    // 传入表单数据，调用验证方法
    if (!this.FrmValidate.checkForm(data)) {
      const error = this.FrmValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon: 'none'
      })
      return false
    }
    //车牌号码
    data.PlateNo = self.data.provinceShort + data.PlateNo;

    self.submitOrder(data);
  },
  /**
   *  显示省份选择
   */
  showProvinceSelect: function() {
    let self = this;
    self.setData({
      isShowProvinceSelect: true
    });
  },
  /**
   *  省份选择确定按钮
   */
  onSureClick: function(e) {
    let self = this;
    let value = e.detail.proValue;
    self.setData({
      provinceShort: value,
      isShowProvinceSelect: false
    })
  },
  /**
   *  关闭弹窗示例
   */
  closeImgPopTap: function(e) {
    let self = this;
    self.setData({
      isShowImgPop: false,
      isShowHighZindexMask: false
    })
  },
  /**
   *  显示弹窗示例
   */
  showImgPopTap: function(e) {
    let self = this;
    let exampletype = e.currentTarget.dataset.exampletype;
    self.setData({
      exampleType: exampletype,
      isShowHighZindexMask: true,
      isShowImgPop: true
    })
  },
  /**
   *  图片上传
   */
  upImgTap: function(e) {
    console.log('上传图片');
    let self = this;
    let tempSrc = e.currentTarget.dataset.upimgsrc;
    self.chooseImage(tempSrc);
  },

  /**
  *  图片上传方法
  */
  chooseImage: function (src) {
    let self = this;
    wx.chooseImage({
      count: 1, // 默认1张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        for (let i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.apiBaseUrl + '/RegOrder/FileUpload',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              "FieldName": src
            },
            success: function (res) {
              var data = JSON.parse(res.data);
              console.log(data);
              //判断是上传那个图片
              switch (src) {
                case 'Compulsory':
                  self.setData({
                    Compulsory: data.data
                  })
                  break;
              }
            }
          })
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '上传图片失败',
          icon: 'none'
        })
      }
    })
  },
  /**
   * 图片上传成功以后的预览
   */
  previewImageTap: function(e) {
    let self = this;
    console.log('图片预览');
    let src = e.currentTarget.dataset.upimgsrc;
    let previewImageCurrent;
    switch (src) {
      case 'Compulsory':
        previewImageCurrent = self.data.Compulsory;
        break;
    }
    let previewImageUrls = [];
    //这三张图片只要有一张上传成功，就可以进行图片预览
    if (self.data.Compulsory) {
      previewImageUrls.push(self.data.Compulsory);
    }
    wx.previewImage({
      current: previewImageCurrent, // 当前显示图片的http链接
      urls: previewImageUrls // 需要预览的图片http链接列表
    })
  },
  /**
   *  图片删除
   */
  upImgDelTap: function(e) {
    let self = this;
    let src = e.currentTarget.dataset.src;
    console.log(src);
    self.setData({
      modalHidden: false,
      currentDelImgId: src
    })
  },
  /**
   *  模态框确认按钮点击
   */
  modalSureListener: function() {
    let self = this;
    let src = self.data.currentDelImgId;
    switch (src) {
      case 'Compulsory':
        self.setData({
          modalHidden: true,
          Compulsory: null
        })
        break;
    }
  },
  /**
   *  模态框确认按钮点击
   */
  modalSureListener: function () {
    let self = this;
    let src = self.data.currentDelImgId;
    switch (src) {     
      case 'Compulsory':
        self.setData({
          modalHidden: true,
          Compulsory: null
        })
        break;
    }
  },
  /**
  *  快递方式的选择
  */
  expressTap: function (e) {
    let self = this;
    let expid = e.currentTarget.dataset.expid;
    let fee = e.currentTarget.dataset.fee;
    if (expid == self.data.ExpressCompanyID) {
      return;
    }

    self.setData({
      ExpressCompanyID: expid
    });

    //更新费用
    let prices = [{
      FeeName: '快递费',
      Fee: fee
    }];
    self.evalOrderPrice(prices);
  },
  /**
   *  显示底部价格明细
   */
  toggleBottomPopTap: function () {
    let self = this;
    self.setData({
      isShowMask: !self.data.isShowMask,
      isShowBottomPop: !self.data.isShowBottomPop
    })
  },
  /**
   * 选择地址
   */
  goToAddressListTap: function (e) {
    let addrid = e.currentTarget.dataset.addrid;
    if (parseInt(addrid) > 0) {
      wx.navigateTo({
        url: '/pages/my/myAddress/myAddressList/myAddressList?currentAddressId=' + addrid + '&SourceUrl=Order',
      })
    } else {
      wx.navigateTo({
        url: '/pages/my/myAddress/editAddress/editAddress?SourceUrl=Order',
      })
    }
  },
  /**
   * 验证初始化
   */
  initValidate() {
    // 验证字段的规则
    const rules = {
      UserName: {
        required: true
      },
      IDNum: {
        required: true,
        idcard: true
      },
      UserMobile: {
        required: true,
        tel: true
      },
      PlateNo: {
        required: true,
        plateno: true
      },
      Compulsory: {
        required: true
      },
      MailAddressID: {
          required: true,
          min: 1
      },
      ExpressCompanyID: {
          required: true,
          min: 1
      }
    };

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      UserName: {
        required: '请输入申请人姓名'
      },
      IDNum: {
        required: '请输入申请人身份证号码',
        idcard: '请输入正确身份证号码'
      },
      UserMobile: {
        required: '请输入申请人电话号码',
        tel: '请输入正确的电话号码'
      },
      PlateNo: {
        required: '请输入车牌号码',
        plateno: '请输入正确的车牌号码'
      },
      Compulsory: {
        required: '请上传保险单照片'
      },
      MailAddressID: {
        required: '请选择收件地址',
        min: '请选择收件地址'
      },
      ExpressCompanyID: {
        required: '请选择快递公司',
        min: '请选择快递公司'
      }
    };
    // 创建实例对象
    this.FrmValidate = new FormValidation(rules, messages)
  },
  /**
   * 获取订单金额
   */
  getOrderPrice() {
    let self = this;
    let url = app.apiBaseUrl + "/Common/GetOrderPrice";
    app.httpRequest({
      method: "GET",
      url: url,
      data: {
        cityId: app.locationInfo.cityId,
        bizTypeId: self.data.BizTypeID
      },
      success: function (res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          self.evalOrderPrice(rdata.data);
        } else {
          wx.showToast({
            title: rdata.message,
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 获取默认邮寄地址
   */
  getDefaultAddress() {
    let self = this;
    let url = app.apiBaseUrl + "/MailAddress/GetDefault";
    app.httpRequest({
      method: "GET",
      url: url,
      data: {
        userId: app.userInfo.UserID
      },
      success: function (res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          if (rdata.data) {
            rdata.data.HasDftAddress = true;
            self.setData(rdata.data);
          }
        } else {
          wx.showToast({
            title: rdata.message,
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 获取快递公司
   */
  getExpressFee() {
    let self = this;
    let url = app.apiBaseUrl + "/Common/GetExpressFee";
    app.httpRequest({
      method: "GET",
      url: url,
      data: {
        cityId: app.locationInfo.cityId,
        bizTypeId: self.data.BizTypeID
      },
      success: function (res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          self.setData({
            ExpressList: rdata.data
          });

          //更新快递费用和总费用
          if (rdata.data.length == 1) {
            self.setData({
              ExpressCompanyID: rdata.data[0].ExpressCompanyID
            });
            //更新费用
            let prices = [{
              FeeName: '快递费',
              Fee: rdata.data[0].ExpressFee
            }];
            self.evalOrderPrice(prices);
          }
        } else {
          wx.showToast({
            title: rdata.message,
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 设置总价格
   */
  evalOrderPrice(addList) {
    let self = this;
    let tmps = self.data.FeeList;
    let orderPrice = 0;

    //价格合并
    for (let i = 0; i < addList.length; i++) {
      let isExit = false;
      for (let j = 0; j < tmps.length; j++) {
        if (addList[i].FeeName == tmps[j].FeeName) {
          tmps[j].Fee = addList[i].Fee;
          isExit = true;
          break;
        }
      }
      if (!isExit) {
        tmps.push({
          FeeName: addList[i].FeeName,
          Fee: addList[i].Fee
        });
      }
    }

    //计算总金额
    for (let j = 0; j < tmps.length; j++) {
      orderPrice += parseFloat(tmps[j].Fee);
    }

    self.setData({
      FeeList: tmps,
      OrderPrice: orderPrice
    });
  },
  /**
   * 车牌大写
   */
  plateNoInput(e) {
    let v = e.detail.value;
    this.setData({
      PlateNo: v.toUpperCase()
    });
  },
  /**
   * 提交订单
   */
  submitOrder(data) {
    let self = this;
    data.UserID = app.userInfo.UserID;
    data.CityID = app.locationInfo.cityId;
    data.BizTypeID = self.data.BizTypeID;
    data.OrderPrice = self.data.OrderPrice;
    data.ExpressFee = self.data.ExpressFee;

    let url = app.apiBaseUrl + "/RegOrder/AddOrder";
    app.httpRequest({
      method: "POST",
      url: url,
      data: data,
      success: function (res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          wx.navigateTo({
            url: '/pages/index/mainOperation/order/success/success',
          })
        } else {
          wx.showToast({
            title: rdata.message,
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})